/**
 * Application configuration
 */
import type { ProjectConfig } from '/#/config';
import { project_cfg_key } from '/@/common/constant/cacheConst';
import projectSetting from '/@/settings/projectSetting';

import { updateHeaderBgColor, updateSidebarBgColor } from '/@/config/logics/theme/updateBackground';
import { updateColorWeak } from '/@/config/logics/theme/updateColorWeak';
import { updateGrayMode } from '/@/config/logics/theme/updateGrayMode';
import { updateDarkTheme } from '/@/config/logics/theme/dark';
import { changeTheme } from '/@/config/logics/theme';

import { useAppStore } from '/@/store/modules/app';
import { useLocaleStore } from '/@/store/modules/locale';

import { primaryColor } from '../../../build/config/themeConfig';
import { createLocalStorage } from '/@/common/util/localCache';
import { deepMerge } from '/@/utils';
import { ThemeEnum } from '/@/common/enums/styleEnum';

// Initial project configuration
export function initAppConfigStore() {
  const localeStore = useLocaleStore();
  const appStore = useAppStore();
  const cls = createLocalStorage();
  // debugger
  let projCfg: ProjectConfig = cls.get(project_cfg_key) as ProjectConfig;
  // 合并样式配置，以本地存储为准
  projCfg = deepMerge(projectSetting, projCfg || {});
  const darkMode = appStore.getDarkMode;
  const { colorWeak, grayMode, themeColor, headerSetting: { bgColor: headerBgColor } = {}, menuSetting: { bgColor } = {}, } = projCfg;
  try {
    if (themeColor && themeColor !== primaryColor) {
      changeTheme(themeColor);
    }

    grayMode && updateGrayMode(grayMode);
    colorWeak && updateColorWeak(colorWeak);
  } catch (error) {
    console.log(error);
  }
  appStore.setProjectConfig(projCfg);

  // init dark mode
  updateDarkTheme(darkMode);
  if (darkMode === ThemeEnum.DARK) {
    updateHeaderBgColor();
    updateSidebarBgColor();
  } else {
    headerBgColor && updateHeaderBgColor(headerBgColor);
    bgColor && updateSidebarBgColor(bgColor);
  }
  // init store
  localeStore.initLocale();
}
